Chapter 39 - Terraform Dynamic Blocks
Repeatable nested blocks
Overview
https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks
Demo - NSGs
Git folder 60 - NSG's and security rules are a good example here
# Define Ports as a list in locals block
locals {
ports = [22, 80, 8080, 8081, 7080, 7081]
}
# Create NSG here
resource "azurerm_network_security_group" "mynsg" {
name = "dupos-nsg-1"
location = azurerm_resource_group.myrg.location
resource_group_name = azurerm_resource_group.myrg.name
dynamic "security_rule" {
for_each = local.ports
content {
name = "inbound-rule-${security_rule.key}"
description = "Inbound Rule ${security_rule.key}"
priority = sum([100, security_rule.key])
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = security_rule.value
source_address_prefix = "*"
destination_address_prefix = "*"
}
}